package com.huan.springboot.controller;

import com.huan.springboot.websocket.WebsocketSessionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.yeauty.pojo.Session;

import java.util.List;

/**
 * @author huan.fu
 * @date 2022/4/26 - 15:21
 */
@RestController
public class WebsocketController {

    @Autowired
    private WebsocketSessionRepository websocketSessionRepository;

    @GetMapping("/fetchAllUserIds")
    public List<String> fetchAllUserIds() {
        return websocketSessionRepository.fetchAllUserIds();
    }

    @GetMapping("sendMessage/{userId}")
    public String sendMessage(@PathVariable("userId") String userId,
                              @RequestParam("message") String message) {
        List<Session> sessions = websocketSessionRepository.findSession(userId);
        for (Session session : sessions) {
            session.sendText(message);
        }
        return "发送成功";
    }

    @GetMapping("sendAllMessage")
    public String sendMessage(@RequestParam("message") String message) {
        List<Session> sessions = websocketSessionRepository.findAllSessions();
        for (Session session : sessions) {
            session.sendText(message);
        }
        return "发送成功";
    }
}
